<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Check_http_ip extends CI_Controller {

	private $_php_bin = '/usr/local/php/bin/php';
	
    public function __construct(){
        parent::__construct();
        $this->load->database();
        
    }

    function check($id, $ip, $source){
    	
    	if(empty($id) || empty($ip) || empty($source)){
    		return false;
    	}
    	
    	$url = "http://ip.chinaz.com/getip.aspx";
    	$page = $this->send_http($url, array(), $ip);
    	
    	if($page){
    		echo "+++correct+++id: " . $id . ",ip:" . $ip . ",source:" . $source . "\n";
    	}else{
    		$this->load->model('universal/mobility_ip_model');
    		$this->mobility_ip_model->update_status($id, "http", 0);
    		echo "+++error+++id: " . $id . ",ip:" . $ip . ",source:" . $source . "\n";
    	}
    }
    
    function start(){
    	$this->load->model('universal/mobility_ip_model');
    	
    	$ip_list_status = $this->mobility_ip_model->get_ip_status();
    	
    	foreach ($ip_list_status as $val){
    		
    		$ip = $val['ip'] . ":" . "10008";
    		
    		$file = "/home/www/crawl/public/index.php check_http_ip check {$val['id']} {$ip} {$val['source']}";
    		$command = $this->_php_bin.' '.$file.' >> /root/check.log &';
    		echo $command."\n";
    		exec($command);
    	}
    }
    
    function send_http($url, $post = array(), $ip = "", $timeout = 5, $header = array(), $connecttimeout = 15) {
    
    	$ch = curl_init();
    	curl_setopt($ch, CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0');
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
    	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    
    	if($post){
    		if(is_array($post)){
    			$post = http_build_query($post);
    		}
    
    		curl_setopt($ch, CURLOPT_POST, true);
    		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    	}
    
    	if ($header){
    		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    	}
    
    	if(!empty($ip)) {
    		curl_setopt($ch, CURLOPT_PROXY, $ip);
    		//curl_setopt($ch, CURLOPT_PROXYTYPE , CURLPROXY_SOCKS5);
    		curl_setopt($ch, CURLOPT_PROXYUSERPWD, "ip_proxy:ip_proxy");
    	}
    
    	$rs = curl_exec($ch);
    	$http_info = curl_getinfo($ch);

    	curl_close($ch);
    	if($http_info['http_code'] != 200 && $http_info['http_code'] != 302 ){
    		return false;
    	}
    	return $rs;
    }
}
